package com.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.guli.common.utils.R;
import com.guli.common.vo.MemberTo;
import com.gulimall.order.conf.LoginInterceptor;
import com.gulimall.order.feign.CartFeign;
import com.gulimall.order.feign.MemberFeign;
import com.gulimall.order.vo.ConfirmVo;
import com.gulimall.order.vo.ItemVo;
import com.gulimall.order.vo.MemberAddrVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.gulimall.order.dao.OrderDao;
import com.gulimall.order.entity.OrderEntity;
import com.gulimall.order.service.OrderService;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeign memberFeign;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public ConfirmVo getConfirm() {
        ConfirmVo confirmVo = new ConfirmVo();
        MemberTo memberTo = LoginInterceptor.memberLocal.get();
        //（feign调用 ）
        //查询地址
        R r = memberFeign.getAddrList(memberTo.getId());
        if (r.getCode()!=0){
            return null;
        }
        List<MemberAddrVo> addrs = r.getData(new TypeReference<List<MemberAddrVo>>() {});
        confirmVo.setAddrs(addrs);
        //查询选中的商品并确定价格
        R cartCheckList = cartFeign.getCartCheckList();
        if (r.getCode()!=0){
            return null;
        }
        List<ItemVo> items = cartCheckList.getData(new TypeReference<List<ItemVo>>() {
        });
        confirmVo.setItems(items);
        String token = UUID.randomUUID().toString().replace("-", "");
        //存入redis进行防止重复提交认证（todo查询删除原子性）
        redisTemplate.boundValueOps("order:user"+memberTo.getId()).set(token,30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        return confirmVo;
    }

}